package com.zdkj.subway.check.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.entity.SwAuTvmCashAmountHierarchyDifference;
import com.zdkj.subway.check.entity.SwParamLine;
import com.zdkj.subway.check.entity.SwParamStation;
import com.zdkj.subway.check.mapper.SwAuTvmCashAmountHierarchyDifferenceMapper;
import com.zdkj.subway.check.mapper.SwParamLineMapper;
import com.zdkj.subway.check.mapper.SwParamStationMapper;
import com.zdkj.subway.check.service.SwAuTvmCashAmountHierarchyDifferenceServices;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.LocalDateConverter;
import com.zdkj.subway.check.util.LocalDateTimeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TVM票款差异协查-现金层级差异信息
 */
@Service
@Slf4j
public class SwAuTvmCashAmountHierarchyDifferenceServicesImpl extends ServiceImpl<SwAuTvmCashAmountHierarchyDifferenceMapper, SwAuTvmCashAmountHierarchyDifference> implements SwAuTvmCashAmountHierarchyDifferenceServices {

    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    @Autowired
    private SwAuTvmCashAmountHierarchyDifferenceServices swAuTvmCashAmountHierarchyDifferenceServices;
    @Resource
    private SwAuTvmCashAmountHierarchyDifferenceMapper swAuTvmCashAmountHierarchyDifferenceMapper;
    /**
     * 导出
     * @param
     * @return
     */
    @Override
    public void export(String ids, String tag, SwAuTvmCashAmountHierarchyDifference params, HttpServletResponse response) throws ParseException {
        //线路、站点、支付方式中文名 根据未回馈的查询 差异类型 compare_type = 4 and assist_status =2
        List<SwAuTvmCashAmountHierarchyDifference> records = new ArrayList<>();
        if(ids == null || ids.isEmpty()) {
            Map<String,String> param = new HashMap<>();
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getLineCode())){
                param.put("lineCode",params.getLineCode());
            }else {
                param.put("lineCode", SecurityUtils.getUser().getLineCode());
            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getStationCode())){
                param.put("stationCode",params.getStationCode());
            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getTvmOrder())){
                param.put("tvmOrder",params.getTvmOrder());
            }
            if(params.getSettleTime()!=null){
                param.put("settleTime",  DateFormat.date_ex_str(params.getSettleTime()));
            }
            param.put("assistStatusList","2,3");
            param.put("compareType","3");
            param.put("scFlag","1");
            List<Map<String, Object>> swAuTvmCashAmountHierarchyDifferenceList = swAuTvmCashAmountHierarchyDifferenceMapper.get_xw_SwAuTvmCashAmountHierarchyDifferenceList(param);
            records = getMapList(swAuTvmCashAmountHierarchyDifferenceList);
        }else {
            Map<String,String> param = new HashMap<>();
            param.put("ids",ids);
            List<Map<String, Object>> swAuTvmCashAmountHierarchyDifferenceList = swAuTvmCashAmountHierarchyDifferenceMapper.get_xw_SwAuTvmCashAmountHierarchyDifferenceList(param);
            records = getMapList(swAuTvmCashAmountHierarchyDifferenceList);
        }
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = null;
            WriteSheet writeSheet = null;
                fileName = URLEncoder.encode("TVM层级差异机电协查", "UTF-8");
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuTvmCashAmountHierarchyExcelTemplate.xlsx");
                writeSheet = EasyExcel.writerSheet("TVM层级差异机电协查").build();
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter())
                    .withTemplate(excelTemplateIs).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            //直接写入Excel数据(list是我查询并需导出的数据，并且里面的字段和excel需要导出的字段对应)
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TVM层级差异协查导出失败!");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    /**
     * 组织数据
     * @param res
     * @return
     */
    private List<SwAuTvmCashAmountHierarchyDifference> getMapList(List<Map<String, Object>> res) {
        List<SwAuTvmCashAmountHierarchyDifference> records = new ArrayList<>();
        for (int i = 0; i < res.size(); i++) {
            Map<String, Object> map = res.get(i);
            SwAuTvmCashAmountHierarchyDifference swAuTvmHierarchy = new SwAuTvmCashAmountHierarchyDifference();
            swAuTvmHierarchy.setId((Integer) map.get("id"));
            SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, map.get("lineCode")));
            SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                    .eq(SwParamStation::getLineCode,map.get("lineCode")).eq(SwParamStation::getCode, map.get("stationCode")));
            swAuTvmHierarchy.setLineCode(swParamLine.getName());
            swAuTvmHierarchy.setStationCode(swParamStation.getName());
            swAuTvmHierarchy.setTvmOrder((String) map.get("tvmOrder"));
            swAuTvmHierarchy.setSettleDate(DateFormat.StringTurnLocalDate(map.get("settleTime").toString()));
            //SC售卖金额
            swAuTvmHierarchy.setSaleAmount(getFixed(map.get("saleAmount")));
            //SC充值金额
            swAuTvmHierarchy.setDepositAmount(getFixed(map.get("depositAmount")));
            //SC退款金额
            swAuTvmHierarchy.setErrorRefundAmount(getFixed(map.get("errorRefundAmount")));
            //LC售卖金额
            swAuTvmHierarchy.setBeSaleAmount(getFixed(map.get("beSaleAmount")));
            //LC充值金额
            swAuTvmHierarchy.setBeDepositAmount(getFixed(map.get("beDepositAmount")));
            //LC退款金额
            swAuTvmHierarchy.setBeErrorRefundAmount(getFixed(map.get("beErrorRefundAmount")));
            //回馈售票金额
            swAuTvmHierarchy.setReplySaleMoney(getFixed(map.get("replySaleMoney")));
            //回馈充值金额
            swAuTvmHierarchy.setReplyRechargeMoney(getFixed(map.get("replyRechargeMoney")));
            //回馈退款金额
            swAuTvmHierarchy.setReplyErrorReturnMoney(getFixed(map.get("replyErrorReturnMoney")));
            swAuTvmHierarchy.setType("TVM单台设备层级");
            swAuTvmHierarchy.setReplyStatus(org.springframework.util.StringUtils.isEmpty(String.valueOf(map.get("replyStatus"))) ? "未回馈" : ("0".equals(String.valueOf(map.get("replyStatus"))) ? "未回馈" : "已回馈"));
            swAuTvmHierarchy.setJdReplyReason(StringUtils.isEmpty(map.get("jdReplyReason").toString()) ? " " : (map.get("jdReplyReason").equals("1") ? "系统原因" : "非系统原因"));
            swAuTvmHierarchy.setJdReplyDetail((String) map.get("jdReplyDetail"));
            if(map.get("jdReplyDateTime")!=null){
                swAuTvmHierarchy.setJdReplyDateTime(DateFormat.StringTurnLocalDateTime(map.get("jdReplyDateTime").toString()));
            }
            if(map.get("sendAssistDateTime")!=null){
                swAuTvmHierarchy.setSendAssistDateTime(DateFormat.StringTurnLocalDateTime(map.get("sendAssistDateTime").toString()));
            }
            records.add(swAuTvmHierarchy);
        }
        return records;
    }
    private List<SwAuTvmCashAmountHierarchyDifference> getList(List<SwAuTvmCashAmountHierarchyDifference> swAuTvmHierarchy) {
        List<SwAuTvmCashAmountHierarchyDifference> records = new ArrayList<>();
        BigDecimal zero = new BigDecimal(0.00);
        String empty  = new String();
        String emptys  = null;
        if(CollectionUtils.isNotEmpty(swAuTvmHierarchy)){
            swAuTvmHierarchy.stream().forEach(x -> {
                SwAuTvmCashAmountHierarchyDifference swAu = new SwAuTvmCashAmountHierarchyDifference();
                swAu.setId(x.getId());
                SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, x.getLineCode()));
                SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                        .eq(SwParamStation::getLineCode,x.getLineCode()).eq(SwParamStation::getCode, x.getStationCode()));
                swAu.setLineCode(swParamLine.getName());
                swAu.setStationCode(swParamStation.getName());
                swAu.setTvmOrder(x.getTvmOrder());
                swAu.setSettleDate(DateFormat.DateTurnLocalDate(x.getSettleTime()));
                swAu.setSaleAmount(x.getSaleAmount() == null ? zero :x.getSaleAmount().divide(new BigDecimal(100)));
                swAu.setDepositAmount(x.getDepositAmount() == null ? zero :x.getDepositAmount().divide(new BigDecimal(100)));
                swAu.setErrorRefundAmount(x.getErrorRefundAmount()== null ? zero :x.getErrorRefundAmount().divide(new BigDecimal(100)));
                swAu.setBeSaleAmount(x.getBeSaleAmount() == null ? zero :x.getBeSaleAmount().divide(new BigDecimal(100)));
                swAu.setBeDepositAmount(x.getBeDepositAmount() == null ? zero :x.getBeDepositAmount().divide(new BigDecimal(100)));
                swAu.setBeErrorRefundAmount(x.getBeErrorRefundAmount() == null ? zero :x.getBeErrorRefundAmount().divide(new BigDecimal(100)));
                swAu.setReplySaleMoney(x.getReplySaleMoney() == null ? zero :x.getReplySaleMoney().divide(new BigDecimal(100)));
                swAu.setReplyRechargeMoney(x.getReplyRechargeMoney() == null ? zero :x.getReplyRechargeMoney().divide(new BigDecimal(100)));
                swAu.setReplyErrorReturnMoney(x.getReplyErrorReturnMoney() == null ? zero :x.getReplyErrorReturnMoney().divide(new BigDecimal(100)));
                swAu.setJdReplyReason(StringUtils.isEmpty(x.getJdReplyReason()) ? " " : (x.getJdReplyReason().equals("1") ? "系统原因" : "非系统原因"));
                swAu.setJdReplyDetail(x.getJdReplyDetail());
                if(x.getJdReplyTime()!=null){
                    swAu.setJdReplyDateTime(DateFormat.DateTurnLocalDateTime(x.getJdReplyTime()));
                }
                /*swAu.setJdReplyReason(x.getQfReplyReason() == null ? empty :x.getQfReplyReason());
                swAu.setJdReplyDetail(x.getJdReplyDetail() == null ? empty :x.getJdReplyDetail());
                swAu.setJdReplyTime(x.getJdReplyTime() == null ? new Date() :x.getJdReplyTime());*/
                records.add(swAu);
            });
        }
        return records;
    }

    /**
     * 金额转换
     * @param money
     * @return
     */
    private BigDecimal getFixed(Object money){
        try {
            BigDecimal num = new BigDecimal("100");
            BigDecimal moneyDecimal = new BigDecimal(String.valueOf(money));
            BigDecimal itemMoney = moneyDecimal.divide(num);
            return itemMoney;

        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
}
